#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
依赖库检测脚本
检查 requirements.txt 中所有库是否正确安装
"""

import sys

def check_library(lib_name, import_name=None, description=""):
    """检查单个库的安装状态"""
    if import_name is None:
        import_name = lib_name
    
    try:
        module = __import__(import_name)
        version = getattr(module, '__version__', '未知版本')
        print(f"  ✅ {lib_name:<12} v{version:<10} - {description}")
        return True
    except ImportError:
        print(f"  ❌ {lib_name:<12} {'未安装':<10} - {description}")
        return False
    except Exception as e:
        print(f"  ⚠️  {lib_name:<12} {'错误':<10} - {str(e)}")
        return False

def main():
    """主检测函数"""
    print("=" * 70)
    print("           📦 依赖库安装状态检测")
    print("=" * 70)
    
    print(f"\n🐍 Python 环境:")
    print(f"   版本: {sys.version}")
    print(f"   路径: {sys.executable}")
    
    # 定义需要检测的库
    libraries = [
        # Excel处理库
        ("pandas", "pandas", "数据处理和Excel读写"),
        ("openpyxl", "openpyxl", "Excel 2007+格式支持"),
        ("xlrd", "xlrd", "Excel 97-2003格式支持"),
        
        # PDF处理库
        ("PyPDF2", "PyPDF2", "PDF基础文本提取"),
        ("pdfplumber", "pdfplumber", "PDF表格和文本提取"),
        ("PyMuPDF", "fitz", "PDF全功能处理 (文本/图片)"),
    ]
    
    print(f"\n📚 Excel处理库检测:")
    excel_success = 0
    excel_total = 3
    
    for lib_name, import_name, desc in libraries[:3]:
        if check_library(lib_name, import_name, desc):
            excel_success += 1
    
    print(f"\n📄 PDF处理库检测:")
    pdf_success = 0
    pdf_total = 3
    
    for lib_name, import_name, desc in libraries[3:]:
        if check_library(lib_name, import_name, desc):
            pdf_success += 1
    
    print("\n" + "=" * 70)
    print("                  📊 检测结果总结")
    print("=" * 70)
    
    total_success = excel_success + pdf_success
    total_libraries = excel_total + pdf_total
    
    print(f"📊 总体状态: {total_success}/{total_libraries} 个库已安装")
    print(f"📊 Excel工具: {excel_success}/{excel_total} 个库已安装")
    print(f"📊 PDF工具:   {pdf_success}/{pdf_total} 个库已安装")
    
    # 给出建议
    print(f"\n💡 使用建议:")
    
    if total_success == total_libraries:
        print("   🎉 恭喜！所有库都已正确安装")
        print("   ✨ 您可以使用所有功能")
        print(f"   👉 开始使用: 查看 '文件夹说明.md'")
    
    elif excel_success == excel_total:
        print("   ✅ Excel转换工具可以正常使用")
        if pdf_success == 0:
            print("   ❌ PDF工具无法使用，请安装PDF处理库")
            print("   📥 安装命令: pip install PyPDF2 pdfplumber PyMuPDF")
        else:
            print(f"   ⚠️  PDF工具部分可用 ({pdf_success}/{pdf_total})")
    
    elif pdf_success == pdf_total:
        print("   ✅ PDF读取工具可以正常使用")
        if excel_success == 0:
            print("   ❌ Excel工具无法使用，请安装Excel处理库")
            print("   📥 安装命令: pip install pandas openpyxl xlrd")
        else:
            print(f"   ⚠️  Excel工具部分可用 ({excel_success}/{excel_total})")
    
    else:
        print("   ❌ 部分库未安装，建议执行:")
        print("   📥 pip install -r requirements.txt")
        print("   🔄 然后重新运行此检测脚本")
    
    # 详细的安装建议
    if total_success < total_libraries:
        print(f"\n🛠️  安装失败的库:")
        
        failed_libs = []
        for lib_name, import_name, desc in libraries:
            try:
                __import__(import_name)
            except ImportError:
                failed_libs.append(lib_name)
        
        if failed_libs:
            print("   单独安装命令:")
            for lib in failed_libs:
                print(f"     pip install {lib}")
            
            print(f"\n   如果安装仍然失败，可以尝试:")
            print(f"     pip install --no-cache-dir {' '.join(failed_libs)}")
            print(f"     或者跳过有问题的库，使用其他替代库")
    
    print("\n" + "=" * 70)
    
    return total_success == total_libraries

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1) 